from . import app, ApiGlobalConfig
from fastapi import File, UploadFile
from fastapi.responses import FileResponse, StreamingResponse, RedirectResponse
from boot import IMG_ROOT_DIR
from .model_response import *
from .model_request import *
import os
from mimetypes import guess_type
from resource.index import HTML
from utils import decrypted


# 打开网页重定向
@app.get("/")
async def index():
    return RedirectResponse(url="/index")


# 打开网页
@app.get("/index")
@decrypted(b"SM5-PFHTsn3MkGWr6E4SMdwLG2OHv7seJt-KWR2du5k=")
async def index():
    return HTML


# 获取图标
@app.get("/static/favicon.ico")
async def favicon():
    return FileResponse(IMG_ROOT_DIR + "/favicon.ico")


# 获取默认图
@app.get("/static/hello.png")
async def hello():
    return FileResponse(IMG_ROOT_DIR + "/hello.png")


# 提交文本
@app.post("/text/save", response_model=ResponseModel)
async def text_save(request_obj: RequestModelBase):
    ApiGlobalConfig.text = request_obj.text
    ResponseModel.message = "操作成功"
    return ResponseModel


# 获取文本
@app.post("/text/get", response_model=ResponseModel)
async def text_get():
    ResponseModel.message = ApiGlobalConfig.text
    return ResponseModel


# 获取图片
@app.post("/image/get", response_model=ResponseModel)
async def image_get():
    error = False
    # 检查文件是否存在
    if not os.path.exists(ApiGlobalConfig.img_path):
        error = True
    # 获取文件的 MIME 类型
    mime_type, _ = guess_type(ApiGlobalConfig.img_path)
    if not mime_type or not mime_type.startswith("image/"):
        error = True
    # 以二进制模式读取文件
    def iter_file():
        if error:
            with open(IMG_ROOT_DIR + "/hello.png", "rb") as file:
                yield from file
        else:
            with open(ApiGlobalConfig.img_path, "rb") as file:
                yield from file
    return StreamingResponse(iter_file(), media_type=mime_type)


# 上传图片
@app.post("/image/upload", response_model=ResponseModel)
async def image_upload(file: UploadFile = File(...)):
    # 检查文件是否为图片类型
    if not file.content_type.startswith("image/"):
        ResponseModel.message = "上传的文件不是图片类型"
        return ResponseModel
    # 生成文件保存路径
    file_extension = os.path.splitext(file.filename)[1]  # 获取文件扩展名
    file_path = os.path.join(IMG_ROOT_DIR, "temp", f"uploaded_image{file_extension}")
    ApiGlobalConfig.img_path = file_path
    # 保存图片到服务器
    with open(file_path, "wb") as buffer:
        buffer.write(await file.read())
        ResponseModel.message = "图片上传成功"
        return ResponseModel